package com.neusoft.weekreport.component.bizService.impl;

import com.neusoft.weekreport.component.bizService.BoardBizService;
import com.neusoft.weekreport.component.req.BoardTaskInfo;
import com.neusoft.weekreport.component.req.ExportBoardInfoReq;
import org.apache.poi.hssf.usermodel.HSSFPrintSetup;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.regex.Pattern;

@Service
public class BoadServiceImpl implements BoardBizService {

    @Override
    public void exportBoardInfo(ExportBoardInfoReq req, HttpServletResponse response) throws Exception {
        //生成Excel流文件返回给前端
        String fileName = req.getFileName() + ".xlsx";//文件名称
        response.setContentType("application/vnd.ms-excel;charset = utf-8");//将结果导出为Excel
        response.setHeader("Content-Disposition","attachment;filename=" + new String(fileName.getBytes(),"ISO8859-1"));//将文件作为附件下载
        XSSFWorkbook workbook = writeExcelTaskInfo(req);
        workbook.write(response.getOutputStream());
    }
    public XSSFWorkbook writeExcelTaskInfo(ExportBoardInfoReq req) throws Exception {

        //列宽
        double col = 50;
        //任务内容行宽
        double contentRow = 164;
        //任务内容字号
        short contentSize=18;
        //姓名行宽
        double nameRow = 50;
        //姓名字号
        short nameSize = 26;
        //任务内容一行的字数
        float fontCount= 13.7f;


        List<BoardTaskInfo> boardTaskInfoList = req.getTaskList();

        XSSFWorkbook workbook = new XSSFWorkbook();//创建Excel工作簿对象
        XSSFSheet sheet = workbook.createSheet();//在工作簿中创建工作表对象
        workbook.setSheetName(0, "任务上墙");//设置工作表的名称
        sheet.setDisplayGridlines(false);//隐藏Excel网格线,默认值为true

        //设置打印参数
        XSSFPrintSetup ps = sheet.getPrintSetup();
        ps.setLandscape(true); // 打印方向，true：横向，false：纵向(默认)
        ps.setPaperSize(HSSFPrintSetup.A4_PAPERSIZE); //纸张类型
        ps.setScale((short)75);//设置缩放为10行高

        sheet.setMargin(XSSFSheet.TopMargin,0.7574f);
        sheet.setMargin(XSSFSheet.BottomMargin, 0.7574f);
        sheet.setMargin(XSSFSheet.LeftMargin,0.3937);
        sheet.setMargin(XSSFSheet.RightMargin,0);

        //设置页眉页脚的边距
        ps.setHeaderMargin(0f);
        ps.setFooterMargin(0f);

        short short1 = (short)(contentRow*20);
        short short2= (short)(nameRow*20);

        //设置列宽度
        sheet.setColumnWidth(0,50*256);
        sheet.setColumnWidth(1,50*256);
        sheet.setColumnWidth(2,50*256);
        sheet.setColumnWidth(3,50*256);
        Integer conutRow = boardTaskInfoList.size()/4;
        for(int i=0;i<conutRow;i++){
            Row row01 = sheet.createRow(i*2);//创建第1行
            Row row02 = sheet.createRow(i*2+1);//创建第2行
            row01.setHeight((short) short1);//行高乘以20，
            row02.setHeight((short) short2);//行高乘以20，
            for(int j=0;j<4;j++){
                String task =  boardTaskInfoList.get(i*4+j).getTask();
                String startTime = boardTaskInfoList.get(i*4+j).getStartTime();
                String endTime = boardTaskInfoList.get(i*4+j).getEndTime();
                String time = boardTaskInfoList.get(i*4+j).getTime();
                String person = boardTaskInfoList.get(i*4+j).getPerson();
                String type = boardTaskInfoList.get(i*4+j).getType();

                Cell cell_01 = row01.createCell(j);//一行中的第1个单元格
                cell_01.setCellStyle(setStyleTaskContent(workbook,contentSize));
                cell_01.setCellValue(calculateTaskContent(task,fontCount)+ startTime + "~" + endTime);

                Cell cell_11 = row02.createCell(j);
                cell_11.setCellStyle(setStylePerson(workbook,nameSize));
                if(type.equals("研发") || type.equals("修改bug")){
                    cell_11.setCellValue(person +" " + time + "h"+" code:");
                }else{
                    cell_11.setCellValue(person +" " + time + "h");
                }
            }
        }
        if(boardTaskInfoList.size()%4 != 0){
            Row row01 = sheet.createRow(conutRow*2);//创建第1行
            Row row02 = sheet.createRow(conutRow*2 + 1);//创建第2行
            sheet.setZoom(75);
            row01.setHeight((short) short1);
            row02.setHeight((short) short2);
            for(int k=0;k<boardTaskInfoList.size()%4;k++){
                String task =  boardTaskInfoList.get(conutRow*4+k).getTask();
                String startTime = boardTaskInfoList.get(conutRow*4+k).getStartTime();
                String endTime = boardTaskInfoList.get(conutRow*4+k).getEndTime();
                String time = boardTaskInfoList.get(conutRow*4+k).getTime();
                String person = boardTaskInfoList.get(conutRow*4+k).getPerson();
                String type = boardTaskInfoList.get(conutRow*4+k).getType();
                Cell cell_01 = row01.createCell(k);//一行中的第1个单元格
                cell_01.setCellStyle(setStyleTaskContent(workbook,contentSize));
                cell_01.setCellValue(calculateTaskContent(task,fontCount) + startTime + "~" + endTime);

                Cell cell_11 = row02.createCell(k);
                cell_11.setCellStyle(setStylePerson(workbook,nameSize));
                if(type.equals("前台研发") || type.equals("修改bug") || type.equals("后台研发")){
                    cell_11.setCellValue(person +" " + time + "h"+" code:");
                }else{
                    cell_11.setCellValue(person +" " + time + "h");
                }


            }
        }
        return workbook;
    }

    public String calculateTaskContent(String task,float fontCount){
        Integer rowCount = getExcelCellAutoHeight(task,fontCount);
        String taskResult="";
        switch (rowCount) {
            case 1:
                taskResult = task +"\n\n\n\n";
                break;
            case 2:
                taskResult = task +"\n\n\n";
                break;
            case 3:
                taskResult = task +"\n\n";
                break;
            case 4:
                taskResult = task +"\n";
                break;
            default:
                taskResult = task+"\n";
        }
        return taskResult;
    }
    //设置看板内容样式
    public XSSFCellStyle setStyleTaskContent(XSSFWorkbook workbook,short contentSize){
        //设置单元格字体
        XSSFCellStyle cellStyle = workbook.createCellStyle();//用于设置单元格的显示样式
        cellStyle.setVerticalAlignment(VerticalAlignment.TOP);//垂直居中

        cellStyle.setBorderBottom(BorderStyle.THIN); // 下边框
        cellStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex());
        cellStyle.setBorderLeft(BorderStyle.THIN);// 左边框
        cellStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex());
        cellStyle.setBorderTop(BorderStyle.THIN);// 上边框
        cellStyle.setTopBorderColor(IndexedColors.BLACK.getIndex());
        cellStyle.setBorderRight(BorderStyle.THIN);// 右边框
        cellStyle.setRightBorderColor(IndexedColors.BLACK.getIndex());

        XSSFFont font = workbook.createFont();//创建字体对象
        font.setFontHeightInPoints((short) contentSize);//设置字号大小
        font.setFontName("微软雅黑");//设置字体
        font.setBold(true);//设置粗体
        cellStyle.setFont(font);//将字体设置添加到单元格样式中。
        cellStyle.setWrapText(true);
        return cellStyle;
    }
    //设置看板经办人样式
    public XSSFCellStyle setStylePerson(XSSFWorkbook workbook,short nameSize){
        //设置单元格字体
        XSSFCellStyle cellStyle = workbook.createCellStyle();//用于设置单元格的显示样式
        XSSFColor xssfColor= new XSSFColor(new java.awt.Color(158, 168, 191, 203));
        cellStyle.setFillForegroundColor(xssfColor);
        cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);//垂直居中
        cellStyle.setBorderBottom(BorderStyle.THIN); // 下边框
        cellStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex());
        cellStyle.setBorderLeft(BorderStyle.THIN);// 左边框
        cellStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex());
        cellStyle.setBorderTop(BorderStyle.THIN);// 上边框
        cellStyle.setTopBorderColor(IndexedColors.BLACK.getIndex());
        cellStyle.setBorderRight(BorderStyle.THIN);// 右边框
        cellStyle.setRightBorderColor(IndexedColors.BLACK.getIndex());


        XSSFFont font = workbook.createFont();//创建字体对象
        font.setFontHeightInPoints((short) nameSize);//设置字号大小
        font.setFontName("微软雅黑");//设置字体
        font.setBold(true);//设置粗体
        cellStyle.setFont(font);//将字体设置添加到单元格样式中。
        cellStyle.setWrapText(true);
        return cellStyle;
    }

    //计算行高
    public static Integer getExcelCellAutoHeight(String str, float fontCountInline) {

        float defaultCount = 0.00f;
        for (int i = 0; i < str.length(); i++) {
            float ff = getregex(str.substring(i, i + 1));
            defaultCount = defaultCount + ff;
        }
        return ((int) (defaultCount / fontCountInline) + 1) ;//计算
    }

    public static float getregex(String charStr) {

        if(charStr.equals(" "))
        {
            return 0.3f;
        }
        if (Pattern.compile("^[a-z0-9]+$").matcher(charStr).matches()) {
            return 0.6f;
        }
        // 判断是否为字母或字符
        if (Pattern.compile("^[A-Z]+$").matcher(charStr).matches()) {
            return 0.7f;
        }
        // 判断是否为全角
        if (Pattern.compile("[\u4e00-\u9fa5]+$").matcher(charStr).matches()) {
            return 1.00f;
        }
        //全角符号 及中文
        if (Pattern.compile("[^x00-xff]").matcher(charStr).matches()) {
            return 1.00f;
        }
        return 0.5f;

    }
}
